import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet} from '@fast-crud/fast-crud';
import * as _ from 'lodash-es';
import * as api from './api';
import { request } from '/@/utils/service';
import { dictionary } from '/@/utils/dictionary';
import {inject} from "vue";
import { useRouter } from "vue-router";


// 注释编号:django-vue3-admin-crud355117:代码开始行
// 功能说明:导入多选批量删除需求
import XEUtils from 'xe-utils';
import { nextTick, ref } from 'vue';

import { auth } from '/@/utils/authFunction';

// 注释编号:django-vue3-admin-crud355117:代码结束行

// 功能说明:导入懒加载外键对应的crud进行复用
import DatabaseViewSet  from "/@/views/se_admin/DbaTables/DatabaseViewSet/crud";
// 注释编号:django-vue3-admin__crud450112:代码结束行

//此处为crudOptions配置
export default function ({ crudExpose}: { crudExpose: CrudExpose}): CreateCrudOptionsRet {
	const pageRequest = async (query: any) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		if (row.id) {  
			form.id = row.id;
		}
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

    const exportRequest = async (query: UserPageQuery) => {
		return await api.exportData(query)
	};

		
		// 注释编号:django-vue3-admin-crud402311:代码开始行
		// 功能说明:配置选中行的功能
		
		//记录选中的行
		const selectedRows = ref<any>([]);

		const onSelectionChange = (changed: any) => {
			const tableData = crudExpose.getTableData();
			const unChanged = tableData.filter((row: any) => !changed.includes(row));
			// 添加已选择的行
			XEUtils.arrayEach(changed, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				if (!ids.includes(item.id)) {
					selectedRows.value = XEUtils.union(selectedRows.value, [item]);
				}
			});
			// 剔除未选择的行
			XEUtils.arrayEach(unChanged, (unItem: any) => {
				selectedRows.value = XEUtils.remove(selectedRows.value, (item: any) => item.id !== unItem.id);
			});
		};
		const toggleRowSelection = () => {
			// 多选后，回显默认勾选
			const tableRef = crudExpose.getBaseTableRef();
			const tableData = crudExpose.getTableData();
			const selected = XEUtils.filter(tableData, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				return ids.includes(item.id);
			});
	
			nextTick(() => {
				XEUtils.arrayEach(selected, (item) => {
					tableRef.toggleRowSelection(item, true);
				});
			});
		};

		// 注释编号:django-vue3-admin-crud402311:代码结束行




	return {
		// 注释编号:django-vue3-admin-crud565217:代码开始行
		// 功能说明:这里要配置return，不然crudExpose获取不到
		selectedRows,
		toggleRowSelection,
		// 注释编号:django-vue3-admin-crud565217:代码结束行


		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					add:{
						show:true
					},
					export:{
						show:true,
                        click(){
                            return exportRequest(crudExpose.getSearchFormData())
                        }
					}
				}
			},
            rowHandle:{
				width:160,
				buttons:{
					view:{
						show:true
					},
					edit:{
						show:true
					},
					copy:{
						show:true
					},
					remove:{
						show:true
					}
				}
			},
			viewForm: {
				wrapper: {
					buttons: {
						ok: { show: false },
						cancel: { show: false },
						reset: { show: false },
					},
				},
			},
			search: {
				container: {
					layout: "multi-line"
				},
				col: {
					span: 4
				},
				options: {
					// labelWidth: "100px"
				}
			},
			table: {
				rowKey: 'id', //设置你的主键id， 默认rowKey=id
				onSelectionChange,
				onRefreshed: () => toggleRowSelection(),   // 注释编号:django-vue3-admin-crud255417:需要配置toggleRowSelection
				// size: "small",
			},
			columns: {
				// 注释编号:django-vue3-admin-crud260511:代码开始行
				// 功能说明:要配置出来$checked
				$checked: {
					title: "选择",
					form: { show: false },
					column: {
						type: "selection",
						align: 'center',
						width: '40px',  // 注释编号:django-vue3-admin-crud340311:这个宽度你要按照自己的页面为调整，不然会出现一个display: inline-flex，导致无法居中显示
						columnSetDisabled: true, //禁止在列设置中选择
					}
				},
				// 注释编号:django-vue3-admin-crud260511:代码结束行
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				database: {
					title: '数据库',
					type: 'dict-select',
					search: { 
						component: {
							placeholder: '键入SID选择数据库',
							clearable: true,
							filterable:true,
						},
						show: true
					},
                    dict: dict({
						isTree: true,
						value: 'id',
						label: 'name',
						getNodesByValues: async (values: any[]) => {
							if (!values.includes("")) {
								const fieldList = ["id", "name"]
								return request({
									url: '/api/DatabaseViewSet/' + "getbyIds/",
									method: "post",
									data: { values, fieldList }
								}).then((ret: any) => {
									return ret.data;
								});
							}
						},
					}),
					column: {
                        align: "center",
						minWidth: 120,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: '' }],
						component: {
							placeholder: '请选择数据库',
							rowKey: "id", //element-plus 必传
							createCrudOptions: DatabaseViewSet,
							filterable: true,
							props: {
								props: {
									value: 'id',
									label: 'name',
								},
							},
						},
					},
				},
				name: {
					title: '链接名称',
					type: 'input',
					search: { show: true },
					column: {
                        align: "center",
						minWidth: 180,
						sortable: true,
					},
					form: {
						rules: [{ required: true, message: '' }],
						component: {},
					},
				},
                owner: {
					title: '拥有者',
					type: 'input',
					search: { show: false },
					column: {
                        align: "center",
						minWidth: 180,
						sortable: false,
					},
					form: {
						component: {
							placeholder: '',
						},
					},
				},
                link_to: {
					title: '目标数据库',
					type: 'input',
					search: { show: true },
					column: {
                        align: "center",
						width: 120,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: '' }],
						component: {},
					},
				},
				link_to_ip: {
					title: '目标IP',
					type: 'input',
					search: { show: true },			
					column: {
                        align: "center",
						width: 120,
						sortable: 'custom',
					},
					form: { 
						// helper: '请输入IP地址格式如192.168.1.1',
						rules: [{ pattern:/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/, message: '格式如192.168.1.1或255.255.255.0'},
							{ required: true, message: '主机IP必填' }
						],
						component:{},
					},
				},
				link_to_port: {
					title: '目标端口',
					type: 'number',
					search: { show: false },
					column: {
                        align: "center",
						minWidth: 100,
						sortable: false,
					},
					form: {
						component: {
							placeholder: '',
						},
					},
				},
				link_type: {
					title: '类型',
					type: 'input',
					search: { show: false },
					column: {
                        align: "center",
						width: 160,
						sortable: false,
					},
					form: {
						component: {
							placeholder: '',
						},
					},
				},
				user_mapping: {
					title: '用户映射',
					type: 'input',
					search: { show: true },
					column: {
                        align: "center",
						minWidth: 120,
						sortable: true,
					},
					form: {
						component: {
							placeholder: '',
						},
					},
				},
				status: {
					title: '状态',
					type: 'dict-select',
					search: { show: true },
					dict: dict({
						data: [{ label: 'Valid', value: 'valid', color: 'success', }, { label: 'Invalid', value: 'invalid', color: 'danger', }, ],
					}),
					column: {
                        align: "center",
						width: 80,
						sortable: false,
					},
					form: {
						component: {
							placeholder: '',
						},
					},
				},
				create_form: {
					title: '创建单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form: {
						component: {},
					},
				},
				remove_form: {
					title: '移除单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form: {
						component: {},
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'date',
					search: { show: false },
					column: { 
						minWidth: 160,
						sortable: 'custom',
						align: "center",
					},
					form:{ show: false },
				},
			},
		},
	};
}
